package classes.io;

import org.junit.Test;

import java.io.*;

/**
 * 随机文件读取、写入
 * 需要byte格式
 */
public class RandomAccessFileTest {
    @Test
    public void test() {
        RandomAccessFile file = null;
        try {
            file = new RandomAccessFile("./src/classes/io/a.txt", "rw");
            //组合拳！实现尾部追加！
            file.seek(file.length());//找到末尾
            file.write("end".getBytes(), 0, 3); //加内容加入
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() {
        RandomAccessFile file = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            file = new RandomAccessFile("./src/classes/io/a.txt", "r");
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("./src/classes/io/d.txt"));
            byte[] bytes = new byte[10]; // 缓存数组
            while (file.read(bytes) != -1) {
                bufferedOutputStream.write(bytes); // 会出点问题
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file != null){
                try {
                    file.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(bufferedOutputStream != null){
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
